<template>
  <div class="commodity-order-admin">
    <!-- 查询区域 -->
    <el-card style="margin-bottom: 10px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="订单ID" label-width="80px">
            <el-input v-model="queryParams.id" placeholder="请输入订单ID" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品ID" label-width="80px">
            <el-input
              v-model="queryParams.commodityId"
              placeholder="请输入商品ID"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户ID" label-width="80px">
            <el-input v-model="queryParams.userId" placeholder="请输入用户ID" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" label-width="80px">
            <el-input v-model="queryParams.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="支付状态" label-width="80px">
            <el-select
              v-model="queryParams.payStatus"
              placeholder="请选择支付状态"
            >
              <el-option label="已支付" :value="1" />
              <el-option label="未支付" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单物流状态" label-width="120px">
            <el-select
                v-model="queryParams.orderStatus"
                placeholder="请选择物流状态"
            >
              <el-option label="未支付" :value="0" />
              <el-option label="待发货" :value="1" />
              <el-option label="已发货" :value="2" />
              <el-option label="已完成" :value="3" />
              <el-option label="已取消" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="20px">
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="getCommodityOrderList"
              >查询</el-button
            >
            <el-button type="primary" @click="showAddDialog" :icon="Promotion">

            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 订单列表表格 -->
    <el-card>
      <el-table
        :data="commodityOrderList"
        style="width: 100%"
        :loading="loading"
      >
        <el-table-column prop="id" label="订单ID" fixed  width="190"/>
        <el-table-column prop="commodityId" label="商品ID" width="190" />
        <el-table-column prop="userName" label="用户名" width="100" />
        <el-table-column prop="userPhone" label="用户电话" width="130"  />
        <el-table-column prop="address" label="目的地址" width="130"  />
        <el-table-column prop="buyNumber" label="购买数量" />
        <el-table-column prop="paymentAmount" label="支付金额" />
        <el-table-column prop="payStatus" label="支付状态">
          <template #default="{ row }">
            <el-tag :type="row.payStatus === 1 ? 'success' : 'danger'">
              {{ row.payStatus === 1 ? "已支付" : "未支付" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="logistics" label="物流单号"  width="100">
          <template #default="{ row }">
            <div v-if="row.logistics">
              <!-- 点击图片触发查看大图 -->
              <el-image
                  style="width: 80px; height: 50px; cursor: pointer;"
                  :src="row.logistics"
              :preview-src-list="[row.logistics]"
              fit="cover"
              preview-teleported
              />
              <!-- 物流单号（截断显示，悬停时显示完整单号） -->
              <el-tooltip :content="row.logistics" placement="top">
                <el-text truncated style="max-width: 100px;">
                  <spqn style="color: #d55c5c">物流号:</spqn>{{ row.logistics }}
                </el-text>
              </el-tooltip>
            </div>
            <span v-else style="color: #999;">还未发货</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="物流状态">
          <template #default="{ row }">
            <el-tag
                :type="getStatusType(row.orderStatus)"
            >
              {{ getStatusText(row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="160"  />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column label="操作" fixed="right" width="240" >
          <template #default="{ row }">

<!--            订单状态：0-未支付 1-待发货 2-已发货 3-已完成 4-已取消-->
            <el-tag type="info" v-if="row.orderStatus === 0" >等待支付</el-tag>
            <el-button type="warn" v-if="row.orderStatus === 1" @click="showEditDialog(row.id)">去发货</el-button>
            <el-tag type="primary" v-if="row.orderStatus === 2" >已发货</el-tag>
            <el-tag type="success" v-if="row.orderStatus === 3" >订单已经完成</el-tag>
            <el-tag type="danger" v-if="row.orderStatus === 4" >订单取消</el-tag>


          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15, 20]"
        :current-page="paginationConfig.current"
        :total="paginationConfig.total"
        :page-size="paginationConfig.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

<!---物流单号上传-->
    <el-dialog v-model="dialogVisible" title="发货信息" width="500px">

          <el-upload
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :auto-upload="false"
              :on-change="handleFileChange"
              class="logistics-uploader"
          >
            <img
                v-if="logisticsImage!==''"
                :src="logisticsImage"
                class="uploaded-image"
                style="height: 128px; width: 128px;"
                alt=""/>
            <!-- 未上传时的占位区域 -->
            <div v-else class="upload-placeholder">
              <el-icon :size="36"><Plus /></el-icon>
              <span>上传物流凭证</span>
            </div>
          </el-upload>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmSend">确认发货</el-button>
      </template>
    </el-dialog>





  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElTag,
  FormInstance,
  ElSelect,
  ElOption
} from "element-plus";
import { Promotion } from "@element-plus/icons-vue";
import {
  addCommodityOrderUsingPost,
  deleteCommodityOrderUsingPost,
  getCommodityOrderVoByIdUsingGet,
  listCommodityOrderVoByPageUsingPost,
  updateCommodityOrderUsingPost
} from "@/api/commodityOrderController";
import request from "@/utils/request";

// 查询参数
const queryParams = ref({
  id: undefined, //订单id
  commodityId: undefined,
  userId: undefined,
  payStatus: undefined, //支付状态
  orderStatus: undefined,//订单状态
});


//物流状态显示
const getStatusType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'info'
  };
  return typeMap[status] || 'info';
};

const getStatusText = (status) => {
  const textMap = {
    0: '未支付',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  };
  return textMap[status] || '未知状态';
};
// 订单列表
const commodityOrderList = ref([]);
const loading = ref<boolean>(false);

// 分页配置
const paginationConfig = ref({
  pageSize: 10,
  total: 0,
  current: 1
});



// 获取订单列表
const getCommodityOrderList = async () => {
  loading.value = true;
  try {
    const res = await request.post("/api/commodityOrder/my/list/order",{
      ...queryParams.value,
      current: paginationConfig.value.current,
      pageSize: paginationConfig.value.pageSize
    });
    //@ts-ignore
    if (res.code === 200) {
      commodityOrderList.value = res.data.records;
      paginationConfig.value.total = parseInt(res.data.total);
    } else {
      ElMessage.error("获取订单列表失败");
    }
  } catch (error) {
    ElMessage.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    id: undefined,
    commodityId: undefined,
    userId: undefined,
    payStatus: undefined,
    orderStatus: undefined
  };
  getCommodityOrderList();
};




// 分页处理
const handleSizeChange = (size: number) => {
  paginationConfig.value.pageSize = size;
  getCommodityOrderList();
};

const handleCurrentChange = (page: number) => {
  paginationConfig.value.current = page;
  getCommodityOrderList();
};


// 初始化加载订单列表
onMounted(() => {
  getCommodityOrderList();
});

//物流图片上传
const dialogVisible = ref(false);  // 控制弹框显示
const currentOrderId = ref(null);  // 当前订单ID
const formData = ref({            // 表单数据
  logisticsImage: '',                   // 物流单号
});

// 点击 "去发货" 按钮时触发
const showEditDialog = (orderId) => {
  dialogVisible.value = true;
  currentOrderId.value = orderId;
};


// 确认发货，调用接口
const handleConfirmSend = async () => {
  if (logisticsImage.value === ''|| logisticsImage.value === null) {
    ElMessage.warning('请上传物流图片');
    return;
  }

  try {
   let data={
     id: currentOrderId.value,
     logistics: logisticsImage.value,
   }

    const res = await request.post('/api/commodityOrder/send', data);
    console.log("上传物流图片成功!",res)
    //@ts-ignore
    if (res.code===200) {
      ElMessage.success('发货成功');
      dialogVisible.value = false;
      //遍历数据 修改状态
      commodityOrderList.value.forEach((item) => {
        //@ts-ignore
        if (item.id === currentOrderId.value) {
          //@ts-ignore
          item.orderStatus = 2; // 修改订单状态为已发货
          //@ts-ignore
          item.logistics = logisticsImage.value;
        }
      });

    } else {
      ElMessage.error(res.data.message || '发货失败');
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后重试');
    console.error(error);
  }
};
//

const logisticsImage = ref('');
//// 文件选择变化时触发
const handleFileChange = (file) => {

  uploadFile(file.raw)
}
// 自定义上传函数
const uploadFile = async (file) => {
  try {
    const form = new FormData();
    form.append('file', file);

    // 调用自定义API
    const response = await request.post('/api/file/upload', form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
    });

    console.log("图片上传 res is ", response);
    // 上传成功处理
    //@ts-ignore
    if (response.code === 200) {
      console.log("上传成功");
      //编辑

      logisticsImage.value = response.data;

      ElMessage.success('上传成功');
      console.log("上传成功");
    } else {
      ElMessage.error(response.data.message || '上传失败');
    }
  } catch (error) {
    console.error('上传错误:', error);
    //@ts-ignore
    ElMessage.error('上传失败: ' + (error.message || '网络错误'));
  }
};

const beforeImageUpload = (file: File) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
  }
  return isImage
}





</script>

<style scoped>
.commodity-order-admin {
  padding: 20px;
}
/* 上传组件容器 */
.logistics-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
  width: 128px;
  height: 128px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

/* 悬停效果 */
.logistics-uploader:hover {
  border-color: #409eff;
}

/* 已上传图片样式 */
.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 上传占位区域 */
.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
  font-size: 12px;
  gap: 8px;
}
</style>
